import { onUnmounted } from 'vue'
import * as signalR from '@microsoft/signalr'
// import domain from '@/utils/domain'

/** 处理sockect长链接请求
 * 注意： 如果是地址是横线隔开，需要转为驼峰
 * workuser-init ❌， workuserInit ✅
 */
// const baseurl = 'http://10.0.44.94:5004'

/** 创建一个signalR实例
 * url: ws的url
 * onStart: 建立成功的回调
 * */
const useSignalR = ({ url = '/ws/aggregate-chat/workuser', onStart = () => {}, onFail = () => {} }) => {
  const baseurl = process.env.BASE_API
  const linkurl = `${baseurl}${url}`
  const connection = new signalR.HubConnectionBuilder().withUrl(linkurl).configureLogging(signalR.LogLevel.Information).build()

  async function start() {
    try {
      await connection.start().then(()=>onStart()).catch(()=>onFail())
      console.log('SignalR Connected.')
    } catch (err) {
      console.log(err)
      setTimeout(start, 5000)
      return
    }
    // onStart()
  }

  connection.onclose(async () => {
    // await start()
  })

  // Start the connection.
  start()

  onUnmounted(() => {
    connection.stop()
  })

  connection.onclose(() => {
    console.log('#connection onclose#❌')
  })
  connection.onreconnected(() => {
    console.log('#connection onreconnected#📖')
  })
  connection.onreconnecting(() => {
    console.log('#connection onreconnecting#🔒')
  })
  return connection
}

export { useSignalR }
